package com.tianchi.lexiang.util;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.tianchi.lexiang.bean.PublicSong;

public class PublicSongQueryUtil {
	private static final String TAG = "PublicSongQueryUtil";
	private static PublicSongQueryUtil instance = null;
	private SQLiteDatabase db = null;
	
	private PublicSongQueryUtil(){
		db = DBOperator.getInstance().getConnection();
		
	}
	
	public static PublicSongQueryUtil getInstance(){
		if(instance == null){
			instance = new PublicSongQueryUtil();
		}
		return instance;
	}
	
	public void destroyInstance(){
		instance = null;
		db = null;
	}
	
	public PublicSong queryNextPublicSong(int currentId){
		String sql = "select * from T_BDSM_PUBLIC_SONG order by "+PublicSong.COLUMN_ID;
		if(db == null || !db.isOpen()){
			 	db = null;
				db = DBOperator.getInstance().getConnection();
			}
		Cursor mCursor = db.rawQuery(sql, null);
		Log.d(TAG, "queryNextPublicSong sql==>"+sql);
		int count = mCursor.getCount();
		Log.d(TAG, "queryNextPublicSong count =>" + count);
		if (count == 0) {
			Log.e(TAG, "publicsong table has no songs,it's an error");
			mCursor.close();
			return null;
		}
//		sql = "select top 1 ID from T_BDSM_PUBLIC_SONG order by "+PublicSong.COLUMN_ID + " desc";
//		Cursor nCursor = db.rawQuery(sql, null);
//		nCursor.moveToFirst();
//		Log.d(TAG, "[queryNextPublicSong]    nCursor.getInt(0)===>" + nCursor.getInt(0));
		mCursor.moveToLast();
		if (currentId >= mCursor.getInt(0) ) {
			currentId = 0;
			Log.d(TAG, "it's the end song in public song table,so restart from the first song");
		}
		mCursor.moveToPosition(-1);
		int idIndex = mCursor.getColumnIndex(PublicSong.COLUMN_ID);
		PublicSong publicSong = new PublicSong();
		Log.d(TAG, "[queryNextPublicSong]....currentId===>" + currentId);
		while (mCursor.moveToNext()) {
			int id = mCursor.getInt(idIndex);
			if (id > currentId) {
				Log.d(TAG, "[queryNextPublicSong] currentId==>" + currentId);
				Log.d(TAG, "[queryNextPublicSong] id==>" + id);
				publicSong.id = id;
				publicSong.songId = mCursor.getInt(mCursor.getColumnIndex(PublicSong.COLUMN_SONG_ID));
				break;
			}
		}
		Log.d(TAG, "next publicsong ==>"+publicSong);
		mCursor.close();
		return publicSong;
	}
	
}
